'use strict';

const { Controller } = require('egg');
const crypto = require('crypto');

class AdminController extends Controller {
    async login() {
        const { ctx, app } = this;
        ctx.validate({
            username: {
                type: 'string',
                required: true,
                desc: '用户名'
            },
            password: {
                type: 'string',
                required: true,
                desc: '密码',
            }
        });
        let { username, password } = ctx.request.body;
        let admin = await app.model.Admin.findOne({
            where: {
                username
            }
        });
        if (!admin) {
            return ctx.apiError('用户不存在或者已封禁')
        }
        await this.checkPassword(password, admin.password);
        admin = JSON.parse(JSON.stringify(admin));
        // 生成token
        let token = ctx.getToken(admin);
        // 加入缓存中
        if (!await this.service.cache.set('admin_' + admin.id, token)) {
            ctx.throw(400, '登录失败');
        }
        // 返回用户信息和token
        ctx.apiSuccess(token)
    };

    // 验证密码
    async checkPassword(password, hash_password) {
        // 先对需要验证的密码进行加密
        const hmac = crypto.createHash("sha256", this.app.config.crypto.secret);
        hmac.update(password);
        password = hmac.digest("hex");
        let res = password === hash_password;
        if (!res) {
            this.ctx.throw(400, '密码错误');
        }
        return true;
    }

    async updateName() {
        const { ctx, app } = this;
        ctx.validate({
            loginUserName: {
                type: 'string',
                required: true,
                desc: '登录名'
            },
            nickName: {
                type: 'string',
                required: true,
                desc: '昵称'
            }
        });
        let { loginUserName, nickName } = ctx.request.body;
        ctx.authAdmin.username = loginUserName;
        ctx.authAdmin.nickname = nickName;
        await ctx.authAdmin.save();
        return ctx.apiSuccess({ nickName, loginUserName });
    }

    async updatePassword() {
        const { ctx, app } = this;
        ctx.validate({
            newPassword: {
                type: 'string',
                required: true,
                desc: '新密码'
            },
            originalPassword: {
                type: 'string',
                required: true,
                desc: '原密码'
            }
        });
        let { newPassword, originalPassword } = ctx.request.body;
        let adminId = ctx.authAdmin.id;
        let admin = await app.model.Admin.findOne({
            where: {
                id: adminId
            }
        });
        if (!admin) {
            ctx.apiError(400, '当前管理员不存在');
        }
        //验证密码
        await this.checkPassword(originalPassword, admin.password);
        //生成token
        admin = JSON.parse(JSON.stringify(admin));
        let token = ctx.getToken(admin);
        admin.token = token;
        delete admin.password;
        //设置redis缓存
        if (!await this.service.cache.set('admin_' + adminId, token)) {
            ctx.throw(400, '登录失败');
        }
        ctx.authAdmin.password = newPassword;
        await ctx.authAdmin.save();
        return ctx.apiSuccess('更新成功');
    }

    async checkPassword(password, hash_password) {
        const hmac = crypto.createHash("sha256", this.app.config.crypto.secret);
        hmac.update(password);
        password = hmac.digest("hex");
        let res = password === hash_password;
        if (!res) {
            this.ctx.throw(400, '密码错误');
        }
        return true;
    }

    async logout() {
        let { ctx, app } = this;
        let adminId = ctx.authAdmin.id;
        if (!await this.service.cache.remove('admin_' + adminId)) {
            ctx.throw(400, '退出登录失败');
        };
        ctx.apiSuccess('退出成功');
    }

    async profile() {
        const { ctx, app } = this;
        const { id } = ctx.authAdmin;
        let userInfo = {
            loginUserName: '',
            nickName: ''
        }
        let admin = await app.model.Admin.findOne({
            where: {
                id
            }
        });
        if (!admin) {
            return ctx.apiError('用户不存在或者已封禁')
        }
        // 返回用户信息和token
        userInfo.loginUserName = admin.username;
        userInfo.nickName = admin.nickname;
        ctx.apiSuccess(userInfo);
    };
}

module.exports = AdminController;